package com.wanmait.scmdemo.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.wanmait.scmdemo.entity.ProductWarehouse;
import com.wanmait.scmdemo.service.ProductWarehouseService;
import com.wanmait.scmdemo.util.AjaxResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 产品在库存 前端控制器
 * </p>
 *
 * @author wanmait
 * @since 2024-11-26
 */
@RestController
@RequestMapping("/manage/productWarehouse")
public class ProductWarehouseController {

    @Resource
    private ProductWarehouseService productWarehouseService;

    /*lzq 仓库辅助表首页 list*/
    @GetMapping("/assistant/list")
    public AjaxResult list(Integer pageNum, Integer pageSize) {
        return AjaxResult.success(productWarehouseService.assistantPageList(pageNum, pageSize));
    }

    /*lzq 仓库辅助表搜索*/
    @PostMapping("/assistant/list/search")
    public AjaxResult search(String keyword, Integer pageNum, Integer pageSize) {
        System.out.println(keyword + "----" + pageNum + "----" + pageSize);
        return AjaxResult.success(productWarehouseService.search(keyword, pageNum, pageSize));
    }

    /*下载 table信息*/
    @PostMapping("/assistant/downloadData")
    public AjaxResult downloadData(@RequestBody List<ProductWarehouse> warehouseAssistantDTOs) {
        System.out.println(warehouseAssistantDTOs.size());
        warehouseAssistantDTOs.forEach(System.out::println);
        try {
            if (CollUtil.isEmpty(warehouseAssistantDTOs)) {
                System.err.println("数据源为空，请检查输入数据！");
                return AjaxResult.error("没有数据可以导出");
            }

            // 获取用户主目录并创建下载路径
            String userHome = System.getProperty("user.home");
            String fileName = "仓库辅助表_" + System.currentTimeMillis() + ".xlsx";
            Path downloadPath = Paths.get(userHome, "Downloads", fileName);

            // 检查目录是否存在，如果不存在则创建
            File directory = new File(downloadPath.getParent().toString());
            if (!directory.exists()) {
                boolean created = directory.mkdirs();
                if (!created) {
                    System.err.println("无法创建目录：" + directory.getAbsolutePath());
                    return AjaxResult.error("无法创建目录，导出失败");
                }
            }

            String filePath = downloadPath.toString();

            // 创建 ExcelWriter
            ExcelWriter writer = ExcelUtil.getWriter(filePath);

            // 自定义标题别名
            writer.addHeaderAlias("仓库名称", "仓库名称");
            writer.addHeaderAlias("产品名称", "产品名称");
            writer.addHeaderAlias("产品编码", "产品编码");
            writer.addHeaderAlias("品牌", "品牌");
            writer.addHeaderAlias("规格型号", "规格型号");
            writer.addHeaderAlias("单位", "单位");
            writer.addHeaderAlias("录入人", "录入人");
            writer.addHeaderAlias("录入时间", "录入时间");
            writer.addHeaderAlias("更新时间", "更新时间");

            // 只导出设置了别名的字段
            writer.setOnlyAlias(true);

            // 合并单元格后的标题行
            writer.merge(8, "仓库辅助表");

            // 提取需要的字段并转换为 Map 列表
            List<Map<String, Object>> dataList = CollUtil.newArrayList();
            for (ProductWarehouse warehouse : warehouseAssistantDTOs) {
                if (warehouse == null || warehouse.getProductShowEntity() == null || warehouse.getWarehouseEntity() == null) {
                    System.err.println("数据对象中存在空值，请检查数据完整性！");
                    continue;
                }

                Map<String, Object> customRow = new java.util.HashMap<>();
                customRow.put("仓库名称", warehouse.getWarehouseEntity().getName());
                customRow.put("产品名称", warehouse.getProductShowEntity().getProductName());
                customRow.put("产品编码", warehouse.getProductShowEntity().getProductCode());
                customRow.put("品牌", warehouse.getProductShowEntity().getProductBrand());
                customRow.put("规格型号", warehouse.getProductShowEntity().getProductModels());
                customRow.put("单位", warehouse.getProductShowEntity().getPriductUnit());
                customRow.put("录入人", StrUtil.removeAll(warehouse.getEnterPerson(), "<[^>]*>"));
                customRow.put("录入时间", warehouse.getProductShowEntity().getEnterTime());
                customRow.put("更新时间", warehouse.getProductShowEntity().getUpdateTime());

                dataList.add(customRow);
            }

            if (CollUtil.isEmpty(dataList)) {
                System.err.println("提取的数据列表为空，请检查字段映射逻辑！");
                return AjaxResult.error("提取的数据列表为空");
            }

            // 写入数据
            writer.write(dataList, true);

            // 自动调整列宽
            for (int i = 0; i < writer.getColumnCount(); i++) {
                writer.autoSizeColumn(i);
            }

            // 关闭 writer，释放内存
            writer.close();

            System.out.println("文件已成功导出到: " + filePath);
            return AjaxResult.success("下载成功").put("filePath", filePath);

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("导出文件时发生错误: " + e.getMessage());
            return AjaxResult.error("导出失败：" + e.getMessage());
        }
    }
}
